/* Overview: This is the code for CBLs ingress control module. The Arduino takes wiegand data from the card reader,
	and passes it along to the server which authenticates the card and passes a response to the arduino, which in turn controls the door.
   Author: Coty Janz
   Date: 31/07/2014
*/	 

//template<class T> inline Print &operator <<(Print &obj, T arg) { obj.print(arg); return obj; }	//Allows us to write succinct code for the serial output.

volatile int bitCounter;
volatile unsigned long bitStore; 

boolean stringComplete = false;
String inputString = "";


void int0ISR(void) {
	bitCounter++;
	bitStore = bitStore << 1;
}

void int1ISR(void) {
	bitCounter++;
	bitStore = bitStore << 1;
	bitStore |= 1;
}


void setup() {
	Serial.begin(9600);
	inputString.reserve(1);

	attachInterrupt(0, int0ISR, RISING);
	attachInterrupt(1, int1ISR, RISING);
	delay(10);

	//pulse to each line to get interrupts working. ATmega misses first negative pulse, as the interrupts are already high.
	for(int i =2; i<4; i++) {
		pinMode(i, OUTPUT);
		digitalWrite(i, HIGH);
		digitalWrite(i, LOW);

		pinMode(i, INPUT);
		digitalWrite(i, HIGH);  //enable internal pull up
	}
	delay(10); 

	bitCounter = 0;
	bitStore = 0;	

	pinMode(13, OUTPUT);
	digitalWrite(13, LOW);
}

void loop() {
	if(bitCounter >= 26) {
		int idNumber = (bitStore >> 1) & 0x3fff;
		int siteNumber = (bitStore >> 17) & 0x3ff; 

		Serial.print(idNumber);
		Serial.print(";");		//character to let the PI know that the whole number has been recieved.

		bitCounter = 0;
		bitStore = 0;	
		delay(500);
	}

	if(stringComplete) {
		//This sequence is very temporary and will be changed once testing is complete
		if (inputString.equals("y")){

			for (int i = 0; i <= 5; i++) {
			digitalWrite(13, HIGH);
			delay(300);
			digitalWrite(13, LOW);;
			delay(300);
			}
		}

		inputString = "";
		stringComplete = false;
	}
}

void serialEvent() {			//The arduino will automatically call this function after loop() if there is data in the serial buffer.
	while (Serial.available()) {			
		char inChar = (char)Serial.read();

		if (inChar == ';') {
			stringComplete = true;
		} else {
			inputString += inChar;
		}
	}
}
